/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.eng.scc.core.parts;

import com.eng.scc.core.data.Device;
import com.eng.scc.core.schema.Schema;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author Rafael
 */
public class DeviceTable extends JTable
{
    private TableModel tableModel = new TableModel();
    
    private List<Device> devices = new ArrayList<Device>();
    
    public DeviceTable()
    {
        setModel( tableModel );
    }
    
    public List<Device> getDevices()
    {
        return devices;
    }

    public void setDevices( List<Device> devices )
    {
        this.devices = devices;
        
        tableModel.fireTableDataChanged();
    }

    public void addDevice( Device d )
    {
        this.devices.add( d );
        
        tableModel.fireTableDataChanged();
    }

    public Device getSelectedDevice()
    {
        if ( getSelectedRow() >= 0 )
        {
            return devices.get( getSelectedRow() );
        }
        
        return null;
    }

    public void updateDevice( Device d )
    {
        devices.remove( getSelectedRow() );
        devices.add( getSelectedRow(), d );
        
        tableModel.fireTableDataChanged();
    }
    
    public class TableModel extends AbstractTableModel
    {
        private SimpleDateFormat df = new SimpleDateFormat( "dd/MM/yyyy" );
        
        @Override
        public String getColumnName( int column )
        {
            if ( column == 0 )
            {
                return "Serial";
            }
            
            else
            {
                return "Data Instalação";
            }
        }
        
        @Override
        public int getRowCount()
        {
            return devices.size();
        }

        @Override
        public int getColumnCount()
        {
            return 2;
        }

        @Override
        public Object getValueAt( int rowIndex, int columnIndex )
        {
            if ( columnIndex == 0 )
            {
                return devices.get( rowIndex ).getSerial();
            }
            
            else
            {
                if ( devices.get( rowIndex ).getInstallationDate() == null )
                {
                    return "n/d";
                }
                
                return df.format( devices.get( rowIndex ).getInstallationDate() );
            }
        }
    }
}
